package com.cw.jeeyt.common.utils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HtmlGenerator {
    private static Logger logger = LoggerFactory.getLogger(HtmlGenerator.class);

    public static String generate(String templatePath, String templateName, Map<String, Object> variables) throws Exception {
        String htmlStr = "";
        BufferedWriter writer = null;
        try {
            Configuration config = FreemarkerConfiguration.getConfiguation(templatePath);
            config.setDefaultEncoding("UTF-8");
            Template tp = config.getTemplate(templateName);
            tp.setEncoding("UTF-8");
            tp.setOutputEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            writer = new BufferedWriter(stringWriter);
            tp.process(variables, writer);
            htmlStr = stringWriter.toString();
            logger.info("生成html文本内容：{}", htmlStr);
        } catch (Exception e) {
            logger.error("生成html文本出错：" + e.getMessage());
            throw new Exception(e);
        } finally {
            writer.flush();
            writer.close();
        }
        return htmlStr;
    }

    public static void main(String[] args) throws Exception {
        Map<String,Object> params = new HashMap<>();
        params.put("package","com.cw.jeeyt");
        String htmlStr = HtmlGenerator.generate("D:/chenweiProject/scaffold/","AbstractClientTest.ftl",params);
        FileOutputStream fos = new FileOutputStream("D:/chenweiProject/scaffold/AbstractClientTest.java");
        fos.write(htmlStr.getBytes());
        fos.close();
    }

}
